﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.Text;


public partial class PlayoffsResultsPerMachine : System.Web.UI.Page
{
    public const char SCORE_DELIMITER = ',';
    public string HTMLOUT;
    public int[] Scores;
    public Tournament oTour;
    //public List<int> oDiferentPkMachines = new List<int>();
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            Configuration rootWebConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
            Scores = (int[])Session["PlayOffsScores"];

            AjaxPro.Utility.RegisterTypeForAjax(typeof(PlayoffsResultsPerMachine));
            Session["POMTimer2"] = Convert.ToInt32(rootWebConfig.AppSettings.Settings["milisecondsToShowMachines"].Value);
            
            if (Request.QueryString["id"] != null)
            {

                int Pk_Tournament = int.Parse(Request.QueryString["id"]);

                Session["POMDiferentPkMachines"] = PlayoffRounds.GetDiferentPkMachinesForPlayoffRounds(Pk_Tournament);

                Session["POMTotalMachineCount2"] = ((List<int>)Session["POMDiferentPkMachines"]).Count;
                Session["POMPk_Tournament2"] = Pk_Tournament;
                Session["POMp_Machine_Number2"] = 1;

                oTour = new Tournament(Pk_Tournament);

            }
            else {
                Response.Write("No tournament selected...");
            }

                      

        }
        catch (Exception Ex) {
            Response.Write(Ex.Message);  
        } 
     
    }
    public void LoadData(int Pk_Tournament,int p_Machine_Number) {
        try
        {
            Tournament oTournament = new Tournament(Pk_Tournament);

            if (Scores == null)
            {
                Configuration rootWebConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
                String[] a = rootWebConfig.AppSettings.Settings["PlayOffsScores"].Value.Split(SCORE_DELIMITER);
                int[] ret = new int[a.Length];
                for (int i = 0; i < a.Length; i++)
                {
                    ret[i] = int.Parse(a[i]);
                }
                Scores = ret;
            }
            //QualifyRounds oQualifyRounds = new QualifyRounds(Pk_Tournament);
            PlayoffRounds oPlayoffRounds = new PlayoffRounds(Pk_Tournament);

            List<PlayoffRound> RoundsWithScore = oPlayoffRounds.GetPlayOffRoundByMachine(p_Machine_Number);
            //Calculamos los puntos


            RoundsWithScore.Sort(new ObjectComparer<PlayoffRound>("Score DESC", true));

            List<Player> oPlayers = new List<Player>(); //Donde almacenamos el total;

            if (RoundsWithScore.Count > 0)
            { //Si hay puntuaciones
                int ScoreCounter = 0; // puntero a la puntuación

                //Calculamos los puntos por maquina y hacemos sumatorio

                for (int x = 0; x < RoundsWithScore.Count; x++)
                {
                    RoundsWithScore[x].PositionInRound = ScoreCounter + 1;

                    if (ScoreCounter < Scores.Length)
                    {  //si le toca puntuación
                        RoundsWithScore[x].PointsInRound = Scores[ScoreCounter];
                        //if (x > 0 && RoundsWithScore[x - 1].Score != RoundsWithScore[x].Score)
                        //{//Verificamos si no es igual a la posicion anterior
                        //    ScoreCounter++;
                        //}
                        //else if (x == 0) {
                        //    ScoreCounter++;
                        //}
                        if (RoundsWithScore[x].Score == 0) //Si está penalizado
                        {
                            RoundsWithScore[x].PointsInRound = 0;
                            RoundsWithScore[x].PositionInRound = 0;
                        }
                        else
                        {
                            if (x > 0 && RoundsWithScore[x - 1].Score != RoundsWithScore[x].Score)
                            {//Verificamos si no es igual a la posicion anterior

                                ScoreCounter++;
                            }
                            else if (x == 0)
                            {

                                ScoreCounter++;
                            }
                            else
                            {
                                //Repeticion de puntuaciones
                                RoundsWithScore[x].PointsInRound = Scores[ScoreCounter - 1];
                                RoundsWithScore[x].PositionInRound = ScoreCounter;
                            }
                        }
                    }
                    else
                    {
                        RoundsWithScore[x].PointsInRound = 0;
                        ScoreCounter++;
                    }


                }




            }

            RoundsWithScore.Sort(new ObjectComparer<PlayoffRound>("Machine_Number ASC,Score DESC", true));

            Session["POMRoundsWithScore2"] = RoundsWithScore;
           


            //HTMLOUT = drawTable(RoundsWithScore, oPlayers, Rondas, oTournament.QualifyPlayersToPlayOffs );

        }
        catch (Exception Ex) {
            string Error = Ex.ToString();
        }
    }
    public int getUniques(List<PlayoffRound> things)
    {
        Dictionary<int, bool> uniques = new Dictionary<int, bool>();
        foreach (PlayoffRound item in things)
        {  
            if (!(uniques.ContainsKey(item.Pk_Player))){     
                uniques.Add(item.Pk_Player, true); 
            }   
        }   
        return uniques.Count ;   
    }


    public string drawTable(List<PlayoffRound> oQualifyRounds)
    {
        try
        {
     
            if (oQualifyRounds.Count > 0)
            {

                StringBuilder OutPutHTML = new StringBuilder();
                //OutPutHTML.Append("<table class=\"Lotery\" style=\"width:780px;text-align:left;border:1px solid black;border-collapse: collapse; padding:5px\">");
                OutPutHTML.AppendFormat("<center><div class='Title'>Machine nº {0} - {1} ({2})</div>", oQualifyRounds[0].Machine_Number,Machine.GetMachineByMachineNumber(oQualifyRounds[0].Machine_Number,int.Parse(Session["POMPk_Tournament2"].ToString())).Machine_Name,oQualifyRounds[0].Machine_Acron);
                OutPutHTML.Append("<table class=\"Lotery2\" style=\"text-align:left;margin-top:10px;border:1px solid black;border-collapse: collapse; padding:5px; width:400px\">");
                OutPutHTML.Append("<tr style=\"background-color:#ffffff;border:1px solid black; font-weight:bold\">");
                //Header
                OutPutHTML.Append("<td style='text-align:center'>Position</td>");                
                OutPutHTML.Append("<td>Player</td>");
                OutPutHTML.Append("<td style=\"text-align:right\">Score</td>");
                OutPutHTML.Append("<td style='text-align:center'>Points</td>");   

                int RowColor = 0;

                foreach (PlayoffRound iQualifyRound in oQualifyRounds)
                {

                    //FIN CONTROL PAGINACION

                    if (RowColor % 2 == 0)
                    {
                        OutPutHTML.Append("<tr style=\"background-color:#e6e4e4\">");
                    }
                    else
                    {
                        OutPutHTML.Append("<tr style=\"background-color:#ffffff\">");
                    }

                    OutPutHTML.AppendFormat("<td style=\"text-align:center\">{0}º</td>", iQualifyRound.PositionInRound.ToString());
                    OutPutHTML.AppendFormat("<td><b><img style=\"vertical-align:middle;\" src=\"img/player_flags/b{0}.png\"/>&nbsp;&nbsp;&nbsp; {1}</b> (#{2})</td>", iQualifyRound.Pk_Player_Zone, iQualifyRound.Player_Nick, iQualifyRound.PlayerNumber);
                    OutPutHTML.AppendFormat("<td style=\"text-align:right\">{0}</td>", iQualifyRound.Score.ToString());
                    OutPutHTML.AppendFormat("<td style=\"text-align:center\">{0}</td>", iQualifyRound.PointsInRound.ToString());                   
                    OutPutHTML.Append("</tr>");
                    RowColor++;

                }


                OutPutHTML.Append("</table></center>");
                return OutPutHTML.ToString();
            }
            else
            {
              
                //Aun no hay resultados para esa máquina (va uno por detras)
                 StringBuilder OutPutHTML = new StringBuilder();
                 List<int> oDiferentPkMachines = (List<int>)Session["POMDiferentPkMachines"];
                 Machine oMachine = new Machine(oDiferentPkMachines[(int)Session["POMp_Machine_Number2"] - 1]);  //Machine.GetMachineByMachineNumber((int)Session["p_Machine_Number2"]-1, (int)Session["Pk_Tournament2"]);
                //OutPutHTML.Append("<table class=\"Lotery\" style=\"width:780px;text-align:left;border:1px solid black;border-collapse: collapse; padding:5px\">");
                 OutPutHTML.AppendFormat("<center><div class='Title'>Machine nº {0} - {1} ({2})</div>", oMachine.Machine_Number, oMachine.Machine_Name, oMachine.Machine_Acron);
                OutPutHTML.Append("<table class=\"Lotery2\" style=\"text-align:left;margin-top:10px;border:1px solid black;border-collapse: collapse; padding:5px; width:400px\">");
                OutPutHTML.Append("<tr style=\"background-color:#ffffff;border:1px solid black; font-weight:bold\">");
                //Header
                OutPutHTML.Append("<td style='text-align:center'>Position</td>");
                OutPutHTML.Append("<td>Player</td>");
                OutPutHTML.Append("<td style=\"text-align:right\">Score</td>");
                OutPutHTML.Append("<td style='text-align:center'>Points</td>");
                OutPutHTML.Append("</tr>");
                OutPutHTML.Append("</table></center>");
                 return OutPutHTML.ToString();
            }      
        }
        catch (Exception Ex) {
            return "ERROR" + Ex.ToString();
        } 
    }

    [AjaxPro.AjaxMethod(AjaxPro.HttpSessionStateRequirement.Read)]
    public string GetTable()
    {
        try
        {


            LoadData((int)Session["POMPk_Tournament2"], ((List<int>)Session["POMDiferentPkMachines"])[(int)Session["POMp_Machine_Number2"] - 1]);


            string res = drawTable((List<PlayoffRound>)Session["POMRoundsWithScore2"]);

            Session["POMp_Machine_Number2"] = ((int)Session["POMp_Machine_Number2"]) + 1;
            if ((int)Session["POMTotalMachineCount2"] < (int)Session["POMp_Machine_Number2"])
            {
                Session["POMp_Machine_Number2"] = 1;
            }

           
            return res;
        }
        catch(Exception)
        {
            return string.Empty;
        }
    }
}

